package cn.snmp.mutual.adapter.impl;


import cn.snmp.mutual.nms.SnmpString;
import cn.snmp.mutual.nms.SnmpVar;
import cn.snmp.mutual.adapter.GeneralMibNodeAdapter;
import cn.snmp.mutual.data.ObjService;

/**
 * @author dengkn
 * MIB NODE Adapter ，extends GeneralMibNodeAdapter
 * 在读取和写入snmp mib node 的时候实现readMibData、writeMibData方法
 * IpAddressMibNodeAdapter 256位置的IP解析
 */
public class IpAddressMibNodeAdapter extends GeneralMibNodeAdapter {

    @Override
    public String readMibData(SnmpVar snmpVar, ObjService mibnode) {

        StringBuffer sb = new StringBuffer();
        int len = 4;
        byte strByteList[] = snmpVar.toBytes();
        for (int i = 0; i < len; i++) {
            String strIp = String.valueOf(strByteList[i]);
            if (strIp == null) {
                return "";
            }
            int iIp = Integer.parseInt(strIp);
            if (strIp.contains("-")) {
                iIp = iIp + 256;
            }
            sb.append(iIp);
            if (i != len - 1)
                sb.append(".");
        }
        String returnString = sb.toString();
        if ("".equalsIgnoreCase(returnString))
            return "0";
        else
            return sb.toString();
    }

    @Override
    public SnmpVar writeMibData(String value, ObjService mibnode) {
        StringBuffer sb = null;
        SnmpVar snmpVar = null;
        if (value.length() > 0) {
            String[] ipArray = value.split("\\.");
            byte[] bArr = new byte[4];

            sb = new StringBuffer();
            for (int i = 0; i < ipArray.length; i++) {
                int octIp = Integer.parseInt(ipArray[i]);
                String hexIp = Integer.toHexString(octIp);
                sb.append(hexIp);
                bArr[i] = (byte) octIp;
            }

            snmpVar = new SnmpString(bArr);

        }
        return snmpVar;
    }


}
